package com.ruoyi.index.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.audit.domain.Audit;
import com.ruoyi.audit.domain.InventoryAmount;
import com.ruoyi.audit.service.AuditService;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.company.service.ICompanyOtherServer;
import com.ruoyi.index.service.IndexService;
import com.ruoyi.procurement.service.ProcurementServer;
import com.ruoyi.product.domain.Product;
import com.ruoyi.purchase.domain.PurchaseOrder;
import com.ruoyi.purchase.service.PurchaseOrderService;
import com.ruoyi.purchaseReturn.service.IPurchaseReturnService;
import com.ruoyi.sale.domain.SaleorderOrder;
import com.ruoyi.sale.service.ISaleGoodsService;
import com.ruoyi.sale.service.ISaleorderService;
import com.ruoyi.saleReturn.service.ISaleReturnService;
import com.ruoyi.salesInvoice.service.SalesInvoiceService;
import com.ruoyi.slow.domain.Slow;
import com.ruoyi.slow.service.SlowService;
import com.ruoyi.statistics.domain.Statistics;
import com.ruoyi.statistics.service.StatisticsService;
import com.ruoyi.warehousing.domain.Warehousing;
import com.ruoyi.warehousing.service.WarehousingService;
import com.ruoyi.warning.domain.Warning;
import com.ruoyi.warning.service.WarningService;
import org.apache.shiro.crypto.hash.Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class IndexServiceImpl implements IndexService {

    @Autowired // 采购订单
    private PurchaseOrderService purchaseOrderService;
    @Autowired // 采购入库订单
    private ProcurementServer procurementServer;
    @Autowired // 采购退货订单
    private IPurchaseReturnService purchaseReturnService;
    @Autowired // 销售订单
    private ISaleorderService saleOrderService;
    @Autowired // 销货订单
    private ISaleGoodsService saleGoodsService;
    @Autowired // 销售发票
    private SalesInvoiceService saleInvoiceService;
    @Autowired // 销售退货
    private ISaleReturnService saleReturnService;
    @Autowired
    private ICompanyOtherServer companyOtherServer;

    @Autowired
    private AuditService auditService;
    @Autowired
    private WarehousingService warehousingService;
    @Autowired
    private SlowService slowService;
    @Autowired
    private WarningService warningService;
    @Autowired
    private StatisticsService statisticsService;

    @Autowired
    private RedisCache redisCache;

    @Override
    public Map<String, Object> mainData() {
        Long deptID = SecurityUtils.getDeptId();
        // 先取Redis
        Map<String, Object> result = redisCache.getCacheObject(CacheConstants.HOT_KEY + deptID);
        if (null != result && !result.isEmpty()) {
            return result;
        }
        return buildCache(result);
    }
    /** 构建缓存 */
    public Map<String, Object> buildCache(Map<String, Object> result) {

        Long deptID = SecurityUtils.getDeptId();
        result = new HashMap<>();

        // 待审核订单
        ArrayList<Map<String, Object>> pendingReview = new ArrayList<>();
        pendingReview.addAll(purchaseOrderService.pendingReview(deptID));// 采购订单
        pendingReview.addAll(procurementServer.pendingReview(deptID)); // 采购入库订单
        pendingReview.addAll(purchaseReturnService.pendingReview(deptID)); // 采购退货订单
        pendingReview.addAll(saleOrderService.pendingReview(deptID)); // 销售订单
        pendingReview.addAll(saleGoodsService.pendingReview(deptID)); // 销货订单
        pendingReview.addAll(saleInvoiceService.pendingReview(deptID)); // 销售发票
        pendingReview.addAll(saleReturnService.pendingReview(deptID)); // 销售退货
        result.put("pendingReview", pendingReview);

        // 数据看板 -
        result.put("conum",companyOtherServer.selectCountByDeptId(deptID)); // 累计合作单位
        result.put("saleNum", saleGoodsService.selectCountByDeptIDAndStatus(deptID)); // 累计成交单数


        //int conum = companyOtherServer.selectCountByMap(map);
        // 写入Redis
        // redisCache.setCacheObject(CacheConstants.HOT_KEY + deptID, result);
        return result;
    }


    @Override
    public String get() {
        Long companyId = SecurityUtils.getLoginUser().getUser().getCompanyId();
        String result = redisCache.getCacheObject(CacheConstants.HOT_KEY + companyId);
        if (null != result && !result.isEmpty()) {
            return result;
        }
        result = buildCacheNew(result);
        redisCache.setCacheObject(CacheConstants.HOT_KEY + companyId, result, 5, TimeUnit.HOURS);
        return result;
    }
    public String buildCacheNew(String redisCache) {
        SysUser sysUser=SecurityUtils.getLoginUser().getUser();
        Long companyId = SecurityUtils.getLoginUser().getUser().getCompanyId();
        PurchaseOrder purchaseOrder = new PurchaseOrder();
        PurchaseOrder purchaseOrder2 = new PurchaseOrder();
        SaleorderOrder saleorderOrder = new SaleorderOrder();
        Map<String, Object> map = new HashMap<>();
        if (!sysUser.getDeptId().equals(companyId)) {
            purchaseOrder.setUserId(sysUser.getUserId());
            purchaseOrder2.setUserId(sysUser.getUserId());
            saleorderOrder.setSaleorderUserId(sysUser.getUserId());
            map.put("userId", sysUser.getUserId());
        }

        purchaseOrder.setDeptId(companyId);

//        List<PurchaseOrder> list1 = purchaseOrderService.selectPurchaseSupplier(purchaseOrder);
        //待审核订单
        Audit audit = new Audit();
        audit.setCompanyId(companyId);
        audit.setAuditStatus("0");
        List<Audit> list1 = auditService.selectAuditList(audit);

        purchaseOrder2.setSupplierId(sysUser.getCompanyId());
        List<PurchaseOrder> list2 = saleOrderService.selectPurchaseOrderList(purchaseOrder2);
        List<Warehousing> list3 = warehousingService.selectWarehousingWarning();
        List<Slow> list4 = slowService.selectSlowListWhichSpill(new Slow());
        List<Warning> list6 = warningService.selectWarningListWhichLack(new Warning());
        List<Warehousing> list7 = warehousingService.selectWarehousingDe("1");
        saleorderOrder.setDeptId(sysUser.getCompanyId());
        List<SaleorderOrder> list8 = saleOrderService.selectSaleorderOrderList(saleorderOrder);

        Statistics statistics = statisticsService.selectStatisticsToIndex();
        int payCount = warningService.selectPayCount();
        int invoiceCount = warningService.selectInvoiceCount();
        map.put("deptId", sysUser.getCompanyId());
        int conum = companyOtherServer.selectCountByMap(map);
        int kind = list3.size();
        int saleNum = 0;
        for (SaleorderOrder saleorderOrder1 : list8) {
            if ("1".equals(saleorderOrder1.getSaleorderStatus()) || "3".equals(saleorderOrder1.getSaleorderStatus())) {
                saleNum++;
            }
        }
        int sumNum = 0;
        int out = 0;
        BigDecimal saleNumM = new BigDecimal("0");
        if (statistics != null) {
            saleNumM = statistics.getSaleOrderTaxAmount();
            out = statistics.getSumNum();
        }
        for (Warehousing warehousing : list3) {
            sumNum = sumNum + warehousing.getAmount().intValue();
        }
        String data1 = null;
        JSONObject jsonobject = new JSONObject();
        if (list1.size() > 0) {
            data1 = JSON.toJSONString(list1);
        }
        //处理数据 - 封装返回数据
        jsonobject.put("purchaseList", null == data1 ? "" : data1);
        String data2 = null;
        if (list2.size() > 0) {
            data2 = JSON.toJSONString(list2);
        }
        jsonobject.put("purchaseWaitList", null == data2 ? "" : data2);
        String data3 = null;
        if (list6.size() > 0) {
            data3 = JSON.toJSONString(list6);
        }
        jsonobject.put("warehousingWarningList", null == data3 ? "" : data3);
        String data4 = null;
        if (list4.size() > 0) {
            data4 = JSON.toJSONString(list4);
        }
        jsonobject.put("warehousingMoreList", null == data4 ? "" : data4);
        String data5 = null;
        if (list7.size() > 0) {
            data5 = JSON.toJSONString(list7);
        }
        jsonobject.put("ThreeList", null == data5 ? "" : data5);
        jsonobject.put("conum", conum);
        jsonobject.put("kind", kind);
        jsonobject.put("sumNum", sumNum);
        jsonobject.put("out", out);
        jsonobject.put("saleNum", saleNum);
        jsonobject.put("saleNumM", saleNumM);
        jsonobject.put("payCount", payCount);
        jsonobject.put("invoiceCount", invoiceCount);

//        AmountDetailed amountDetailed = auditService.selectAmountDetailed(companyId);
//        if (amountDetailed!=null){
//            jsonobject.put("amountDetailed",amountDetailed.getTaxTotal());
//        }else {
//            jsonobject.put("amountDetailed","-");
//        }
        InventoryAmount inventoryAmount = auditService.selectInventorAmountCount(companyId);
        if (inventoryAmount != null) {
            jsonobject.put("amountDetailed", inventoryAmount.getTaxTotal());
        } else {
            jsonobject.put("amountDetailed", 0);
        }

        Product product=new Product();
        List<Product> warehousingList=warehousingService.selectProductToWar(product);
        product.setDeptId(SecurityUtils.getLoginUser().getUser().getCompanyId());
        jsonobject.put("warehousingList",JSON.toJSONString(warehousingList));

        return jsonobject.toString();
    }

}
